package com.sunny.lock;

import java.util.Queue;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class Producer implements Runnable{

    private Random random = new Random();
    private String name;
    private Queue<Integer> queue;
    private int max;
    private Lock lockProducer;
    private Lock lockConsumer;
    private Condition full;
    private Condition empty;

    public Producer(Lock lockProducer, Lock lockConsumer, Condition full, Condition empty, int max, Queue<Integer> queue, String name) {
        this.lockProducer = lockProducer;
        this.lockConsumer = lockConsumer;
        this.full = full;
        this.empty = empty;
        this.max = max;
        this.queue = queue;
        this.name = name;
    }

    @Override
    public void run() {

        while (true){
            lockProducer.lock();
            try {
                if (queue.size() >= max){
                    full.await();
                }
                queue.offer(random.nextInt(10));
                System.out.println("生产者"+name+"生产了一个产品。当前产品队列长度为："+queue.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lockProducer.unlock();
            }
            if(queue.size() > 0) {
                lockConsumer.lock();
                try {
                    empty.signalAll();
                } finally {
                    lockConsumer.unlock();
                }
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

}
